package com.example.tangjiangxu.a360floatwindowdemo;

import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by tangjiangxu on 2/27/17.
 */

public class FloatWindowService extends Service {
    private static final String TAG = "FloatWindowService";
    /** 用于在子线程中创建或移除悬浮框 **/
    private Handler handler = new Handler();
    /** 定时器，定时进行检测当前应该创建还是移除悬浮框 **/
    private Timer timer;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.e(TAG, "onBind: ");
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand: ");
        //开启定时器，每隔0.5s刷新一次
        if (timer == null) {
            timer = new Timer();
            timer.scheduleAtFixedRate(new RefreshTask(), 0, 500);
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //Service被终止的同时，也停止计时器继续运行
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    /** 刷新的任务 **/
    class RefreshTask extends TimerTask {

        @Override
        public void run() {

            //当前页面是桌面，且没有悬浮框显示，则创建悬浮框
            if (isHome() && !MyWindowManager.isWindowShowing()) {
                Log.e(TAG, "run: 当前页面是桌面，且没有悬浮框显示，则创建悬浮框");
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        //创建悬浮框
                        MyWindowManager.createSmallWindow(getApplicationContext());
                    }
                });
            } else if (!isHome() && MyWindowManager.isWindowShowing()){
                Log.e(TAG, "run: 当前不是桌面，且有悬浮框显示，则移除悬浮框");
                //当前不是桌面，且有悬浮框显示，则移除悬浮框
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        //移除小的悬浮框
                        MyWindowManager.removeSmallWindow(getApplicationContext());
                        //移除大的悬浮框
                        MyWindowManager.removeBigWindow(getApplicationContext());
                    }
                });
            } else if (isHome() && MyWindowManager.isWindowShowing()) {
                Log.e(TAG, "run: 当前页面是桌面，且有悬浮框，则刷新悬浮框");
                //当前页面是桌面，且有悬浮框，则刷新悬浮框
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        //刷新悬浮框
                        MyWindowManager.updateUsedPercent(getApplicationContext());
                    }
                });
            }


        }
    }

    /**
     * 判断当前页面是否是桌面
     * @return
     */
    private boolean isHome() {
        ActivityManager mActivityManager = (ActivityManager)(getApplicationContext(). getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningTaskInfo> rti = mActivityManager.getRunningTasks(1);
        String topActivityName = rti.get(0).topActivity.getPackageName();
        Log.e(TAG, "isHome: topActivityName：" + topActivityName);
        return getHomes().contains(topActivityName);
    }

    /**
     * 获得属于桌面的应用的程序包名称
     * @return 返回包含所有包名的字符串列表
     */
    private List<String> getHomes() {
        List<String> names = new ArrayList<String>();
        PackageManager packageManager = this.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo ri : resolveInfo) {
            Log.e(TAG, "getHomes: activityInfo.packageName：" + ri.activityInfo.packageName);
            names.add(ri.activityInfo.packageName);
        }
        return names;
    }
}
